package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.DTO.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-13
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    @Override
    public LoginVo export(UserLoginRequestDto userLoginRequestDto) {
        //获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //获取openID
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        //随机生成名字
        String randomed = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX);

        //判断新增还是更新
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openid).one();
        if (ObjectUtil.isNull(familyMember)) {
            //新增
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            familyMember.setOpenId(openid);
            familyMember.setName(randomed + phone.substring(7));
            this.save(familyMember);

        }else {
            //更新不同的手机号
            if (!familyMember.getPhone().equals(phone)) {
                familyMember.setPhone(phone);
                this.updateById(familyMember);
            }
        }

        //获取token
        HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("userId",familyMember.getId());
        tokenMap.put("nickName",familyMember.getName());

        String token = tokenService.createToken(tokenMap);


        return LoginVo.of(token,familyMember.getName());
    }


}
